package com.want.buss.interfaces.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import com.want.buss.interfaces.po.MogoDBSequence;
import com.want.buss.interfaces.po.WsdlStatus;
import com.want.buss.interfaces.service.IWsdlStatusService;

@Service
public class WsdlStatusServiceImpl implements IWsdlStatusService{

	@Autowired
    private MongoTemplate mongoTemplate;
	
    public void insert(WsdlStatus wsdlStatus) {
        mongoTemplate.insert(wsdlStatus);
    }

    public List<WsdlStatus> queryAll(WsdlStatus wsdlStatus){
        Criteria criteria = new Criteria();
        Query query = BasicQuery.query(criteria);
        return mongoTemplate.find(query, WsdlStatus.class);
    }

    public WsdlStatus queryOne(WsdlStatus wsdlStatus){
        Long sid =wsdlStatus.getSid();
        Query query = BasicQuery.query(Criteria.where("sid").is(sid));
        return mongoTemplate.findOne(query, WsdlStatus.class);
    }

    public void updateOne(WsdlStatus wsdlStatus){ 
        Long sid =wsdlStatus.getSid();
        Update update = new Update();
        if(wsdlStatus.getEndDate()!=null){
            update.set("endDate", wsdlStatus.getEndDate());
        }
        mongoTemplate.updateMulti(Query.query(Criteria.where("sid").is(wsdlStatus.getSid())),update,WsdlStatus.class);
    }
    
    public void delByIds(List<Long> ids){
        ids.stream().forEach(sid -> {
            Query query = BasicQuery.query(Criteria.where("sid").is(sid));
            mongoTemplate.findAndRemove(query, WsdlStatus.class);
        });
    }
    
    /**
     * 获取下一个序列值
     * @param collName
     * @return
     */
    private Long getNextId(String collName) {
		Query query = new Query(Criteria.where("collName").is(collName));
		Update update = new Update();
		update.inc("seqId", 1);
		FindAndModifyOptions options = new FindAndModifyOptions();
		options.upsert(true);
		options.returnNew(true);
		MogoDBSequence seq = mongoTemplate.findAndModify(query, update, options, MogoDBSequence.class);
		return seq.getSeqId();
	}
    
}
